package com.lagou.service.impl;

import com.lagou.dao.CourseMapper;
import com.lagou.domain.Course;
import com.lagou.domain.CourseVO;
import com.lagou.domain.Teacher;
import com.lagou.service.CourseService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;


@Service
public class CourseServiceImpl implements CourseService {
    @Autowired
    private CourseMapper courseMapper;

    /*多条件课程查询*/
    @Override
    public List<Course> findCourseByConditioin(CourseVO courseVO) {
        List<Course> courseList = courseMapper.findCourseByConditioin(courseVO);
        return courseList;
    }

    /*新增课程信息与讲师信息*/
    @Override
    public void saveCourseOrTeacher(CourseVO courseVO) throws InvocationTargetException, IllegalAccessException {
        //封装课程信息
        Course course = new Course();
        //封装讲师信息
        Teacher teacher = new Teacher();

        //通过反射将一个对象的值赋值个另外一个对象（前提是对象中属性的名字相同,前面复制给后面）
        BeanUtils.copyProperties(course, courseVO);
        //补全课程信息
        Date date = new Date();
        System.out.println(date);
        course.setCreateTime(date);
        course.setUpdateTime(date);
        //保存课程信息
        courseMapper.saveCourse(course);

        //封装讲师信息
        BeanUtils.copyProperties(teacher, courseVO);
        //获取到新插入数据的id，将其存到老师信息中
        teacher.setCourseId(course.getId());
        teacher.setCreateTime(date);
        teacher.setUpdateTime(date);
        //保存老师信息
        courseMapper.saveTeacher(teacher);

    }

    /*回显课程信息(根据id查询对应的课程信息及关联的讲师信息)*/
    @Override
    public CourseVO findCourseById(Integer id) {
        return courseMapper.findCourseById(id);
    }


    /*修改课程及讲师信息*/
    @Override
    public void updateCourseOrTeacher(CourseVO courseVO) throws InvocationTargetException, IllegalAccessException {
        //封装课程信息
        Course course = new Course();
        //封装讲师信息
        Teacher teacher = new Teacher();

        Date date = new Date();

        //通过反射将一个对象的值赋值个另外一个对象（前提是对象中属性的名字相同,前面复制给后面）
        BeanUtils.copyProperties(course, courseVO);
        //补全课程信息
        course.setUpdateTime(date);
        //更新课程信息
        courseMapper.updateCourse(course);

        //封装讲师信息
        BeanUtils.copyProperties(teacher, courseVO);
        //获取到更新数据的id，将其存到老师信息中
        teacher.setCourseId(course.getId());
        teacher.setUpdateTime(date);
        //更新老师信息
        courseMapper.updateTeacher(teacher);
    }

    /*修改课程状态*/
    @Override
    public void updateCourseStatus(Integer id, Integer status) {
        Course course = new Course();

        Date date = new Date();

        course.setId(id);
        course.setStatus(status);
        course.setUpdateTime(date);

        courseMapper.updateCourseStatus(course);
    }

}